from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.datasets import fetch_lfw_people

# 加载LFW人像数据集
lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
X, y = lfw_people.data, lfw_people.target

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 使用KNN分类器
knn_classifier = KNeighborsClassifier(n_neighbors=5)
knn_classifier.fit(X_train, y_train)
y_pred_knn = knn_classifier.predict(X_test)
accuracy_knn = accuracy_score(y_test, y_pred_knn)
print(f'KNN Accuracy: {accuracy_knn}')

# 使用SVM分类器
svm_classifier = SVC(kernel='linear')
svm_classifier.fit(X_train, y_train)
y_pred_svm = svm_classifier.predict(X_test)
accuracy_svm = accuracy_score(y_test, y_pred_svm)
print(f'SVM Accuracy: {accuracy_svm}')

# 使用PCA进行数据降维
pca = PCA(n_components=100)  # 选择降维后的维度
X_train_pca = pca.fit_transform(X_train)
X_test_pca = pca.transform(X_test)

# 使用LDA进行数据降维
lda = LinearDiscriminantAnalysis(n_components=min(X_train.shape[1], len(np.unique(y_train)) - 1))
X_train_lda = lda.fit_transform(X_train, y_train)
X_test_lda = lda.transform(X_test)

# 使用KNN分类器（PCA降维）
knn_classifier_pca = KNeighborsClassifier(n_neighbors=5)
knn_classifier_pca.fit(X_train_pca, y_train)
y_pred_knn_pca = knn_classifier_pca.predict(X_test_pca)
accuracy_knn_pca = accuracy_score(y_test, y_pred_knn_pca)
print(f'KNN with PCA Accuracy: {accuracy_knn_pca}')

# 使用SVM分类器（PCA降维）
svm_classifier_pca = SVC(kernel='linear')
svm_classifier_pca.fit(X_train_pca, y_train)
y_pred_svm_pca = svm_classifier_pca.predict(X_test_pca)
accuracy_svm_pca = accuracy_score(y_test, y_pred_svm_pca)
print(f'SVM with PCA Accuracy: {accuracy_svm_pca}')

# 使用KNN分类器（LDA降维）
knn_classifier_lda = KNeighborsClassifier(n_neighbors=5)
knn_classifier_lda.fit(X_train_lda, y_train)
y_pred_knn_lda = knn_classifier_lda.predict(X_test_lda)
accuracy_knn_lda = accuracy_score(y_test, y_pred_knn_lda)
print(f'KNN with LDA Accuracy: {accuracy_knn_lda}')

# 使用SVM分类器（LDA降维）
svm_classifier_lda = SVC(kernel='linear')
svm_classifier_lda.fit(X_train_lda, y_train)
y_pred_svm_lda = svm_classifier_lda.predict(X_test_lda)
accuracy_svm_lda = accuracy_score(y_test, y_pred_svm_lda)
print(f'SVM with LDA Accuracy: {accuracy_svm_lda}')
